package com.cyan.note.service.impl;

import com.cyan.note.dto.admin.ShopCreateRequest;
import com.cyan.note.dto.admin.ShopResponse;
import com.cyan.note.dto.admin.ShopUpdateRequest;
import com.cyan.note.entity.Shop;
import com.cyan.note.entity.User;
import com.cyan.note.mapper.ShopMapper;
import com.cyan.note.mapper.UserMapper;
import com.cyan.note.service.ShopService;
import com.cyan.note.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 店铺服务实现类
 * 超级管理员专用 - 严格遵循数据隔离原则
 * 
 * @author ZhangzhenYu
 * @since 2025-01-14
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ShopServiceImpl implements ShopService {

    private final ShopMapper shopMapper;
    private final UserMapper userMapper;

    /**
     * 有效的店铺状态
     */
    private static final List<String> VALID_STATUSES = Arrays.asList("active", "suspended", "closed");

    @Override
    public List<ShopResponse> getAllShops() {
        log.info("超级管理员查询所有店铺基础信息");
        List<Shop> shops = shopMapper.selectAllBasicInfo();
        return shops.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }

    @Override
    public List<ShopResponse> getShopsByStatus(String status) {
        log.info("超级管理员按状态查询店铺列表, status: {}", status);
        
        // 验证状态参数
        if (!VALID_STATUSES.contains(status)) {
            throw new IllegalArgumentException("无效的店铺状态: " + status);
        }
        
        List<Shop> shops = shopMapper.selectByStatus(status);
        return shops.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }

    @Override
    public ShopResponse getShopById(Long id) {
        log.info("超级管理员查询店铺基础信息, shopId: {}", id);
        
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("无效的店铺ID");
        }
        
        Shop shop = shopMapper.selectById(id);
        if (shop == null) {
            throw new RuntimeException("店铺不存在");
        }
        
        return convertToResponse(shop);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ShopResponse createShop(ShopCreateRequest request) {
        log.info("超级管理员创建新店铺, name: {}, code: {}", request.getName(), request.getCode());
        
        // 1. 验证店铺编号是否已存在
        if (isCodeExists(request.getCode())) {
            throw new RuntimeException("店铺编号已存在: " + request.getCode());
        }
        
        // 2. 获取当前操作用户（超级管理员）
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            throw new RuntimeException("无法获取当前用户信息");
        }
        
        // 3. 构建店铺实体
        Shop shop = new Shop();
        BeanUtils.copyProperties(request, shop);
        shop.setStatus("active"); // 新创建的店铺默认为活跃状态
        shop.setCreatedBy(currentUserId);
        
        // 4. 保存到数据库
        int result = shopMapper.insert(shop);
        if (result <= 0) {
            throw new RuntimeException("创建店铺失败");
        }
        
        log.info("店铺创建成功, shopId: {}, name: {}, code: {}", shop.getId(), shop.getName(), shop.getCode());
        
        // 5. 返回创建结果
        return convertToResponse(shop);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ShopResponse updateShop(ShopUpdateRequest request) {
        log.info("超级管理员更新店铺基础信息, shopId: {}", request.getId());
        
        // 1. 检查店铺是否存在
        Shop existingShop = shopMapper.selectById(request.getId());
        if (existingShop == null) {
            throw new RuntimeException("店铺不存在");
        }
        
        // 2. 构建更新实体（只更新允许的字段）
        Shop updateShop = new Shop();
        updateShop.setId(request.getId());
        updateShop.setName(request.getName());
        updateShop.setDescription(request.getDescription());
        updateShop.setContactPhone(request.getContactPhone());
        
        // 3. 执行更新
        int result = shopMapper.updateBasicInfo(updateShop);
        if (result <= 0) {
            throw new RuntimeException("更新店铺信息失败");
        }
        
        log.info("店铺信息更新成功, shopId: {}", request.getId());
        
        // 4. 返回更新后的信息
        return getShopById(request.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateShopStatus(Long id, String status) {
        log.info("超级管理员更新店铺状态, shopId: {}, status: {}", id, status);
        
        // 1. 验证参数
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("无效的店铺ID");
        }
        
        if (!VALID_STATUSES.contains(status)) {
            throw new IllegalArgumentException("无效的店铺状态: " + status);
        }
        
        // 2. 检查店铺是否存在
        Shop existingShop = shopMapper.selectById(id);
        if (existingShop == null) {
            throw new RuntimeException("店铺不存在");
        }
        
        // 3. 更新状态
        int result = shopMapper.updateStatus(id, status);
        if (result > 0) {
            log.info("店铺状态更新成功, shopId: {}, oldStatus: {}, newStatus: {}", 
                    id, existingShop.getStatus(), status);
            return true;
        } else {
            log.error("店铺状态更新失败, shopId: {}", id);
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteShop(Long id) {
        log.warn("超级管理员删除店铺, shopId: {}", id);
        
        // 1. 验证参数
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("无效的店铺ID");
        }
        
        // 2. 检查店铺是否存在
        Shop existingShop = shopMapper.selectById(id);
        if (existingShop == null) {
            throw new RuntimeException("店铺不存在");
        }
        
        // 3. 执行删除（注意：这是系统级删除，会级联删除相关数据）
        int result = shopMapper.deleteById(id);
        if (result > 0) {
            log.warn("店铺删除成功, shopId: {}, name: {}", id, existingShop.getName());
            return true;
        } else {
            log.error("店铺删除失败, shopId: {}", id);
            return false;
        }
    }

    @Override
    public boolean isCodeExists(String code) {
        if (code == null || code.trim().isEmpty()) {
            return false;
        }
        return shopMapper.countByCode(code.trim()) > 0;
    }

    @Override
    public boolean isCodeExists(String code, Long excludeId) {
        if (code == null || code.trim().isEmpty()) {
            return false;
        }
        if (excludeId == null || excludeId <= 0) {
            return isCodeExists(code);
        }
        return shopMapper.countByCodeExcludeId(code.trim(), excludeId) > 0;
    }

    /**
     * 转换Shop实体为响应DTO
     */
    private ShopResponse convertToResponse(Shop shop) {
        if (shop == null) {
            return null;
        }
        
        ShopResponse response = new ShopResponse();
        BeanUtils.copyProperties(shop, response);
        
        // 设置创建者名称
        if (shop.getCreatedBy() != null) {
            User creator = userMapper.selectById(shop.getCreatedBy());
            if (creator != null) {
                response.setCreatedByName(creator.getRealName());
            }
        }
        
        return response;
    }
}